package com.github.pig.admin.controller.zhgl.house;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.exception.excel.ExcelImportException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.admin.model.zhgl.house.UnitHouse;
import com.github.pig.admin.model.zhgl.unit.BuildingUnit;
import com.github.pig.admin.service.zhgl.building.ICommunityBuildingService;
import com.github.pig.admin.service.zhgl.house.IUnitHouseService;
import com.github.pig.admin.service.zhgl.unit.IBuildingUnitService;
import com.github.pig.admin.util.AjaxJson;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.util.R;
import com.github.pig.common.web.BaseController;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * ���ݻ�����Ϣ 前端控制器
 * </p>
 *
 * @author xiaosa
 * @since 2018-06-04
 */
@Controller
@RequestMapping("/unitHouse")
public class UnitHouseController extends BaseController {

    @Autowired
    private IUnitHouseService unitHouseService;
    @Autowired
    private IBuildingUnitService buildingUnitService;
    @Autowired
    private ICommunityBuildingService communityBuildingService;

    /**
    * 通过ID查询
    *
    * @param id ID
    * @return UnitHouse
    */
    @GetMapping("/{id}")
    public R<UnitHouse> get(@PathVariable Integer id) {
        return new R<>(unitHouseService.selectById(id));
    }

    /**
    * 分页查询信息
    *
    * @param params 分页对象
    * @return 分页对象
    */
    @RequestMapping("/page")
    @ResponseBody
    public Page page(@RequestParam Map<String, Object> params, UnitHouse unitHouseWhere) {
        EntityWrapper entityWrapper = new EntityWrapper<BuildingUnit>();
        Object existUnit = params.getOrDefault("existUnit", 1);
        Page<UnitHouse> page = new Page<UnitHouse>(Integer.parseInt(params.getOrDefault("page", 1).toString())
                , Integer.parseInt(params.getOrDefault("limit", 10).toString()));
        //拼装条件
        initCondition(params,entityWrapper,unitHouseWhere,existUnit);
        return unitHouseService.selectPage(page, entityWrapper.orderBy("sort", true));

    }

    private void initCondition(Map<String, Object> params, EntityWrapper entityWrapper, UnitHouse unitHouseWhere,Object existUnit) {
        entityWrapper.eq("del_flag", CommonConstant.STATUS_NORMAL);
        if(StringUtils.isNotEmpty(unitHouseWhere.getHouseName())){
            entityWrapper.like("house_name",unitHouseWhere.getHouseName());
        }
        if("0".equalsIgnoreCase(existUnit.toString())){
            entityWrapper.eq("building_id",unitHouseWhere.getUnitId());
        }else{
            entityWrapper.eq("unit_id",unitHouseWhere.getUnitId());
        }

        entityWrapper.setSqlSelect("id, building_id AS buildingId,(select building_name from community_building where id=building_id) AS buildingName, unit_id AS unitId,(select unit_name from building_unit where id=unit_id) AS unitName,house_name AS houseName, house_type AS houseType,(select label from sys_dict where value = house_type and type = 'house_type') AS houseTypeName, build_size AS buildSize, status,(select label from sys_dict where value = status and type = 'house_status') AS houseStatusName, give_date AS giveDate, file_path AS filePath, use_size AS useSize, proerty_endtime AS proertyEndtime, del_flag AS delFlag,sort,floor");
    }

    /**
     * 添加
     * @param  unitHouse  实体
     * @return success/false
     */
    @RequestMapping("/doAdd")
    @ResponseBody
    public R<Boolean> add(@RequestBody UnitHouse unitHouse) {
        R r = new R();
        if(existHouse(unitHouse.getUnitId(),unitHouse.getHouseName(),null)){
            r.setData(false);
            r.setMsg("房屋名称重复");
            return r;
        }
        unitHouse.setDelFlag(CommonConstant.STATUS_NORMAL);
        r.setData(unitHouseService.insert(unitHouse));
        return r;
    }

    /**
     * 判断房屋名称是否重复
     * @param unitId
     * @return
     */
    public boolean existHouse(String unitId,String houseName,String id){
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
        if(StringUtils.isNotEmpty(id)){
            //说明是修改
            entityWrapper.ne("id",id);
        }
        entityWrapper.eq("unit_id",unitId);
        entityWrapper.eq("house_name",houseName);
        List list = unitHouseService.selectList(entityWrapper);
        if(list!=null&&list.size()>0){
            return true;
        }
        return false;
    }

    /**
     * 删除
     * @param id ID
     * @return success/false
     */
    @RequestMapping("/doDel")
    @ResponseBody
    public AjaxJson delete( String id) {
        AjaxJson json=new AjaxJson();
        UnitHouse unitHouse = unitHouseService.selectById(id);
        unitHouse.setDelFlag(CommonConstant.STATUS_DEL);
        boolean flag = unitHouseService.updateById(unitHouse);
        json.setSuccess(flag);
        if(flag){
            json.setMsg("删除成功!");

        }else{
            json.setMsg("删除失败!");
        }
        return json;
    }

    @RequestMapping("/doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids){
        AjaxJson json=new AjaxJson();
        List<UnitHouse> list = unitHouseService.selectBatchIds(Arrays.asList(ids.split(",")));
        for(UnitHouse bean : list){
            bean.setDelFlag(CommonConstant.STATUS_DEL);
        }
        boolean flag = unitHouseService.updateBatchById(list);
        json.setSuccess(flag);
        if(flag){
            json.setMsg("删除成功!");

        }else{
            json.setMsg("删除失败!");
        }
        return json;
    }

    /**
     * 编辑
     * @param  unitHouse  实体
     * @return success/false
     */
    @RequestMapping("/doUpdate")
    @ResponseBody
    public R<Boolean> edit(@RequestBody UnitHouse unitHouse) {
        R r = new R();
        if(existHouse(unitHouse.getUnitId(),unitHouse.getHouseName(),unitHouse.getId())){
            r.setData(false);
            r.setMsg("房屋名称重复");
            return r;
        }
        r.setData(unitHouseService.updateById(unitHouse));
        return r;
    }

    @RequestMapping("/upload")
    @ResponseBody
    public AjaxJson upload(ModelMap modelMap, HttpServletRequest request, String buildingId,String unitId,String communityId){
        AjaxJson j = new AjaxJson();
        j.setSuccess(true);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setImportFields(UnitHouse.heads);
            try {
                List<UnitHouse> insertList = new ArrayList<>();
                Map<String,String> map = new HashMap<>();
                List<UnitHouse> list = ExcelImportUtil.importExcel(file.getInputStream(),UnitHouse.class,params);
                if(list==null||list.size()==0){
                    j.setMsg("文件空内容。");
                    return j;
                }
                for(UnitHouse bean : list){
                    if(existHouse(unitId,bean.getHouseName(),null)){
                        continue;
                    }
                    if(map.containsKey(bean.getHouseName())){
                        continue;
                    }

                    if(StringUtils.isNotEmpty(communityId)){
                        bean.setCommunityId(communityId);
                    }
                    if(StringUtils.isNotEmpty(buildingId)){
                        bean.setBuildingId(buildingId);
                    }
                    if(StringUtils.isNotEmpty(unitId)){
                        bean.setUnitId(unitId);
                        bean.setBuildingId(buildingId);
                    }
                    map.put(bean.getHouseName(),bean.getHouseName());
                    insertList.add(bean);
                }
                if(insertList!=null&&insertList.size()>0){
                    unitHouseService.insertBatch(insertList);
                }
                j.setMsg("成功导入："+insertList.size()+"行,因房屋名称重复失败"+(list.size()-insertList.size())+"行");
            }catch (ExcelImportException exception){
                j.setSuccess(false);
                j.setMsg("Excel模板不合法或数据格式不正确(日期格式：yyyy-MM-dd)！");
            } catch (Exception e) {
                e.printStackTrace();
                j.setSuccess(false);
                j.setMsg("文件导入失败！");
            }finally{
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }
    /**
     * 根据单元获取房屋列表
     * @return
     */
    @RequestMapping("/getUnitHouses/{unitId}")
    @ResponseBody
    public List<UnitHouse> houseList(@PathVariable String unitId) {
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("unit_id",unitId);
        entityWrapper.eq("del_flag",CommonConstant.STATUS_NORMAL);
        entityWrapper.orderBy("sort",true);
        return unitHouseService.selectList(entityWrapper);
    }

    /**
     * 根据楼宇获取房屋列表
     * @return
     */
    @RequestMapping("/getUnitHousesByBuildingId/{buildingId}")
    @ResponseBody
    public List<UnitHouse> getUnitHousesByBuildingId(@PathVariable String buildingId) {
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("building_id",buildingId);
        entityWrapper.eq("del_flag",CommonConstant.STATUS_NORMAL);
        entityWrapper.orderBy("sort",true);
        return unitHouseService.selectList(entityWrapper);
    }


}
